package cn.etg.day07;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 将聊天室服务端今天写的内容独立完成一次，
 * 完成后，修改代码，使得服务端可以一直读取
 * 客户端发送过来的每一条消息并输出到控制台。
 * 
 * 初始化服务端时，读取当前包中server-config.txt文件的第一行，用该端口进行
 * ServerSocket的初始化。
 * @author Xiloer
 *
 */
public class Server {
    ServerSocket serverSocket;

    public Server() {
        try {
            System.out.println("服务端启动中……");
            serverSocket = new ServerSocket(8080);
            System.out.println("服务器启动成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        Socket socket = null;
        InputStream in = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        try {
            System.out.println("等待连接中……");
            socket = serverSocket.accept();
            System.out.println("连接成功");

            in = socket.getInputStream();
            isr = new InputStreamReader(in);
            br = new BufferedReader(isr);

            String str;
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}
